package gdepot

import grails.converters.JSON

import javax.persistence.criteria.Order

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
import groovy.json.JsonOutput

@Transactional(readOnly = true)
class TransactionRecordController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def TransactionService transactionService
    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond TransactionRecord.list(params), model:[transactionRecordInstanceCount: TransactionRecord.count()]
    }

    def show(TransactionRecord transactionRecordInstance) {
        respond transactionRecordInstance
    }

    def create() {
        respond new TransactionRecord(params)
    }
    @Transactional
    def save(TransactionRecord transactionRecordInstance) {
        if (transactionRecordInstance == null) {
            notFound()
            return
        }

        if (transactionRecordInstance.hasErrors()) {
            respond transactionRecordInstance.errors, view:'create'
            return
        }

        transactionRecordInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'transactionRecord.label', default: 'TransactionRecord'), transactionRecordInstance.id])
                redirect transactionRecordInstance
            }
            '*' { respond transactionRecordInstance, [status: CREATED] }
        }
    }

    def edit(TransactionRecord transactionRecordInstance) {
        respond transactionRecordInstance
    }

    @Transactional
    def update(TransactionRecord transactionRecordInstance) {
        if (transactionRecordInstance == null) {
            notFound()
            return
        }

        if (transactionRecordInstance.hasErrors()) {
            respond transactionRecordInstance.errors, view:'edit'
            return
        }

        transactionRecordInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'TransactionRecord.label', default: 'TransactionRecord'), transactionRecordInstance.id])
                redirect transactionRecordInstance
            }
            '*'{ respond transactionRecordInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(TransactionRecord transactionRecordInstance) {

        if (transactionRecordInstance == null) {
            notFound()
            return
        }

        transactionRecordInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'TransactionRecord.label', default: 'TransactionRecord'), transactionRecordInstance.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'transactionRecord.label', default: 'TransactionRecord'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    //---------------------------------------------------------------------------------------------------------------------------------------------------------


    // 选择银行
    def choseBank(){
        def order = Orders.findById(params.orderId)
        def bankList = Bank.findAll()
        return [bankList:bankList,order: order]
    }

    def prepareForPayment(){
        def bank = Bank.findByCode(params.bankCode)
        def order = Orders.findById(params.orderId)
        def accountBank = AccountBank.findByBankCardNoAndCellphone(params?.bankCardNo,params?.cellphone)
        return [accountBankInstance:accountBank , bank:bank,order: order]
    }
    //快捷支付的五要素签约

    @Transactional
    def sendFiveElementsQuickPay(){
        println "sendFiveElementsQuickPay"
        if(!params || !params.name || !params.bankCode || !params.bankCardNo || !params.certificateType || !params.idCard || !params.cellphone)
        {
            println "1-->"
            println "name:${params.name},bankCode:${params.bankCode},bankCardNo:${params.bankCardNo},certificateType:${params.certificateType},certificateNo:${params.idCard},cellphone:${params.phone}, reservedCellphone:${params.cellphone}"
            flash.message = '信息填写不完整'
            redirect action: 'verifyInformation'
        }

        def name = params.name
        def bankCode = params.bankCode
        def bankCardNo = params.bankCardNo
        def certificateType = params.certificateType

        def idCard = params.idCard
        def phone = params.phone         //用户注册时使用的手机号
        def cellphone = params.cellphone   //银行预留手机号

//        def user = User.findByFullNameAndPhone(name,phone)
        def user = User.findByFullNameAndEmail(name,params.email)
        if(user == null){
            println "用户不存在！"
//            def errors = [status: 400,errorCode:402, message:'用户不存在']
//            render  JsonOutput.toJson(errors)
//            return
            flash.message = '用户不存在!'
            redirect action: 'prepareForPayment' ,params:[bankCardNo:bankCardNo,cellphone:cellphone,bankCode:bankCode]

        }
        def bank = Bank.findByCode(bankCode)
        if(bank == null){
            println "银行暂未开通"
            def errors = [status: 400,errorCode:403, message:'银行暂未开通']
            render  JsonOutput.toJson(errors)
            return
            flash.message = '银行暂未开通'
            redirect action: 'prepareForPayment' ,params:[bankCardNo:bankCardNo,cellphone:cellphone,bankCode:bankCode]

        }
        def accountBank = AccountBank.findByBankCardNoAndIdCardAndCellphone(bankCardNo,idCard,cellphone)
        if(!accountBank){
            //将数据保存到AccountBank表中
            accountBank = new AccountBank()
            accountBank.account = user
            accountBank.bank = bank
            accountBank.status = 'FAILED' //  初始状态为未通过
            accountBank.isPrimary = false
            accountBank.bankCardNo = bankCardNo
            accountBank.fullName = name
            accountBank.cellphone = cellphone
            accountBank.certificateType = certificateType
            accountBank.idCard = idCard
            if (accountBank.validate())
            {
                accountBank.save flush: true
            }
            else
            {
                println '****************'
                println accountBank.errors
//                render ([status: 400, message:"信息填写不正确"] as JSON)
                flash.message = '信息填写不正确'
                redirect action: 'prepareForPayment' ,params:[bankCardNo:bankCardNo,cellphone:cellphone,bankCode:bankCode]
            }
        }

        def result = transactionService.sendFiveElementsQuickPay(name, bankCode, bankCardNo, certificateType, idCard, cellphone) //cellphone
        def responseCode = result.responseCode
//        def responseCode =  '000000'
        def responseDescription = result.responseDescription
        println 'response desc: ' + responseDescription
        println "responseCode:${responseCode}"
        if(responseCode == '0000'){
            println 'responseDescription: ' + responseDescription
//            render ([status: 200, message:"验证码发送成功，请注意查收"] as JSON)
            flash.message = '验证码发送成功，请注意查收'
            redirect action: 'prepareForPayment' ,params:[bankCardNo:bankCardNo,cellphone:cellphone,bankCode:bankCode]
        }
        else
        {
//            render ([status: 400, message:"签约失败:${responseDescription}"] as JSON)
            flash.message = "签约失败:${responseDescription}"
            redirect action: 'prepareForPayment' ,params:[bankCardNo:bankCardNo,cellphone:cellphone,bankCode:bankCode]

        }
        return
    }
    //代收付的手机验证码验证，增加一个手机号, 这块app传过来的不一定是银行预留手机号，但是我们给fuiou发过去的一定是银行预留手机号

    @Transactional
    def verifyInformation(){

        if(!params || !params.cellphone || !params.verifyCode || !params.bankCardNo )
        {
            flash.message = "信息填写不完整"
            redirect action: 'prepareForPayment' ,params:[bankCardNo:params.bankCardNo,cellphone:params.cellphone,bankCode:params.bankCode]
        }

        def order = Orders.findById(params.orderId)
//        def cellphone = params.phone                //手机号
        def cellphone = params.cellphone// 银行预留手机号
        def verifyCode = params.verifyCode              // 客户银行预留手机号收到的验证码
        def bankCardNo = params.bankCardNo              //客户银行卡号

        def accountBank = AccountBank.findByBankCardNoAndCellphone(bankCardNo,cellphone)

        def  result = transactionService.sendVerifyCodeInQuickPay(verifyCode, bankCardNo)
        def responseCode = result.responseCode
        def responseDescription = result.responseDescription
        println "responseCode:${responseCode},responseDescription:${responseDescription}"
        if(responseCode == '0000' && responseDescription.toString().contains('签约已生效'))
        {
            // 将客户银行卡的状态改为正常
            accountBank.status = 'SUCCESS'

            if (accountBank.validate())
            {
                accountBank.save()
                println "custBankerrors:"+accountBank.errors

            }
            else
            {
                println '***************'
                println accountBank.errors
            }
            flash.message = "绑卡成功"
            render view: 'message' ,model: [message: "银行卡绑定成功",accountBank:accountBank]
        }
        else
        {
            flash.message = "绑卡失败：${responseDescription}"
            redirect action: 'prepareForPayment' ,params:[bankCardNo:params.bankCardNo,cellphone:params.cellphone,bankCode:params.bankCode]

        }
        return
    }

    def pay()
    {
        def user = session.user
        def accountBankList = AccountBank.findAllByAccountAndStatus(user,'SUCCESS')
        def order =Orders.findById(params.orderId)
        return [order: order,accountBankList:accountBankList]
    }

    //代收
    @Transactional
    def payForCollection()
    {
        if(!params || !params.accountBankId ||  ! params.orderId )
        {
            flash.message = "信息填写不正确..."
            redirect action: "pay",params: [order: order]
        }

        def order = Orders.findById(params.orderId)
        if(!order)
        {
            flash.message = "找不到对应的订单信息，请您再次确认。"
            redirect action: "pay",params: [order: order]
        }
        def accountBank = AccountBank.findById(params.accountBankId)
        if (!accountBank)
        {
            println "accountBank${params.nameOfAccount}:${params.certificateNo}不存在！"
            flash.message = "找不到对应的账户信息，请再次您确认。"
            redirect action: "pay",params: [order: order]
        }

        def alphabet = '0'..'9'
        def transactionrecord = new TransactionRecord()
        transactionrecord.versionCode = TransactionRecordConfig.version
        transactionrecord.payType  = TransactionRecordConfig.payType
        transactionrecord.orderSerialNumber  = new Date().format('yyyyMMddHHmmss') + transactionService.generator( alphabet.join(), 9 )
        while(TransactionRecord.countByOrderSerialNumber(transactionrecord.orderSerialNumber)>1){
            transactionrecord.orderSerialNumber = new Date().format('yyyyMMddHHmmss') + transactionService.generator( alphabet.join(), 9 );
        }
        transactionrecord.payStatus = 'Tobepaid' // TobePaid
        transactionrecord.accountBank = accountBank
        transactionrecord.order = order
        transactionrecord.transactionAmount = order.price

        if(transactionrecord.validate())
        {
            transactionrecord.save flush: true
            def resultObj = transactionService.payForCollection(accountBank, transactionrecord)
            println "resultObj: --> ${resultObj}"

            def transactionRecordNew = TransactionRecord.findByOrderSerialNumber(resultObj.orderSerialNumber)
            if(transactionRecordNew)
            {
                if (resultObj.responseCode == '000000')
                {
                    transactionRecordNew.responeCode = resultObj.responseCode
                    transactionRecordNew.responeDescription = resultObj.responseDescription
                    transactionRecordNew.payStatus = "Success"
                    if(transactionRecordNew.validate())
                    {
                        transactionRecordNew.save flush:true
                    }else{
                        println 'TransactionRecord save() error:' + transactionRecordNew.errors
                    }

                    //修改订单的支付状态
                    def orderPay = transactionRecordNew.order
                    orderPay.status = "SUCCESS"
                    if(orderPay.validate())
                    {
                        orderPay.save flush:true
                    }
                    render view: 'message',model: [message:"订单支付成功，请等待发货..",state:'sussess']
                }
                else
                {
                    flash.message = "支付失败，请您稍后重试！"
                    render view: 'message',model: [message:"程序猿哥哥开了个小差..",state:'failed']
                }
            }
            else
            {
                flash.message = "找不到对应的信息~~~~~"
                redirect action: "pay",params: [order: order]
            }
        }
        else
        {
            flash.message = "交易信息有误！请你再次确认"
            redirect action: "pay",params: [order: order]
        }
    }

    def message()
    {
    }
}
